package global

import (
	"errors"
	"fmt"
	"os"
	"strings"

	"gopkg.openfuyao.cn/bkeadm/pkg/executor/containerd"
	"gopkg.openfuyao.cn/bkeadm/pkg/executor/docker"
	"gopkg.openfuyao.cn/bkeadm/pkg/executor/exec"
	"gopkg.openfuyao.cn/bkeadm/pkg/executor/k8s"
	"gopkg.openfuyao.cn/bkeadm/utils"
)

var (
	Docker      docker.DockerClient
	Containerd  containerd.ContainerdClient
	K8s         k8s.KubernetesClient
	Command     exec.Executor
	Workspace   string
	CustomExtra map[string]string
)

func init() {
	Command = &exec.CommandExecutor{}
	if utils.IsFile("/opt/BKE_WORKSPACE") {
		f, err := os.ReadFile("/opt/BKE_WORKSPACE")
		if err == nil {
			Workspace = string(f)
			Workspace = strings.TrimSpace(Workspace)
			Workspace = strings.TrimRight(Workspace, "\n")
			Workspace = strings.TrimRight(Workspace, "\r")
			Workspace = strings.TrimRight(Workspace, "\t")
		}
	}
	if os.Getenv("BKE_WORKSPACE") != "" {
		Workspace = os.Getenv("BKE_WORKSPACE")
	}
	if Workspace == "" {
		Workspace = "/bke"
	}
	if !utils.Exists(Workspace + "/tmpl") {
		_ = os.MkdirAll(Workspace+"/tmpl", 0644)
	}
	if !utils.Exists(Workspace + "/volumes") {
		_ = os.MkdirAll(Workspace+"/volumes", 0644)
	}
	if !utils.Exists(Workspace + "/mount") {
		_ = os.MkdirAll(Workspace+"/mount", 0644)
	}
	CustomExtra = make(map[string]string)
}

func TarGZ(prefix, target string) error {
	output, err := Command.ExecuteCommandWithOutput("sh", "-c", fmt.Sprintf("cd %s && tar --use-compress-program=pigz -cf %s .", prefix, target))
	if err != nil {
		return errors.New(output + err.Error())
	}
	return nil
}

func TarGZWithDir(prefix, dir, target string) error {
	output, err := Command.ExecuteCommandWithOutput("sh", "-c", fmt.Sprintf("cd %s && tar "+
		"--use-compress-program=pigz -cf %s ./%s", prefix, target, dir))
	if err != nil {
		return errors.New(output + err.Error())
	}
	return nil
}

// TaeGZWithoutChangeFile tar gz without change file
func TaeGZWithoutChangeFile(prefix, target string) error {
	cmd := fmt.Sprintf("cd %s && tar --use-compress-program=pigz -cf %s . --warning=no-file-changed --ignore-failed-read",
		prefix, target)
	output, err := Command.ExecuteCommandWithOutput("sh", "-c", cmd)
	if err != nil {
		return errors.New(output + err.Error())
	}
	return nil
}

func UnTarGZ(dataFile, target string) error {
	output, err := Command.ExecuteCommandWithOutput("sh", "-c", fmt.Sprintf("tar -xzf %s -C %s", dataFile, target))
	if err != nil {
		return errors.New(output + err.Error())
	}
	return nil
}
